/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2006-2008 Sun Microsystems, Inc.
 * Portions Copyright 2013-2016 ForgeRock AS.
 */
package org.opends.server.loggers;


import org.forgerock.i18n.LocalizableMessage;
import org.opends.messages.Severity;
import org.forgerock.opendj.server.config.server.ErrorLogPublisherCfg;
import org.forgerock.opendj.config.server.ConfigException;
import org.opends.server.core.ServerContext;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.InitializationException;
import org.opends.server.util.StaticUtils;
import org.opends.server.util.TimeThread;

/**
 * This class provides an implementation of an error logger where only messages
 * generated by a specified thread is actually logged.
 */
public class ThreadFilterTextErrorLogPublisher
    extends ErrorLogPublisher<ErrorLogPublisherCfg>
{
  private Thread thread;

  private TextWriter writer;

  /**
   * Construct a new instance with the provided settings.
   *
   * @param thread The thread to log from.
   * @param writer The writer used to write the messages.
   */
  public ThreadFilterTextErrorLogPublisher(Thread thread,
                                           TextWriter writer)
  {
    this.thread = thread;
    this.writer = writer;
  }

  @Override
  public void initializeLogPublisher(ErrorLogPublisherCfg config, ServerContext serverContext)
      throws ConfigException, InitializationException
  {
    // This class should only be used internally in the server and not be
    // configurable via the admin framework.
  }

  @Override
  public void close()
  {
    writer.shutdown();
  }

  @Override
  public void log(String category, Severity severity,
      LocalizableMessage message, Throwable exception)
  {
    if (message != null) {
      Thread currentThread = Thread.currentThread();
      if(this.thread.equals(currentThread) ||
          this.thread.getThreadGroup().equals(currentThread.getThreadGroup()))
      {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append(TimeThread.getLocalTime());
        sb.append("] category=").append(category).
        append(" severity=").append(severity).
        append(" msgID=").append(message.resourceName()).
        append("-").append(message.ordinal()).
        append(" msg=").append(message);
        if (exception != null)
        {
          sb.append(" exception=").append(
              StaticUtils.stackTraceToSingleLineString(exception));
        }

        this.writer.writeRecord(sb.toString());
      }
    }
  }

  @Override
  public boolean isEnabledFor(String category, Severity severity)
  {
    Thread currentThread = Thread.currentThread();
    return this.thread.equals(currentThread)
        || this.thread.getThreadGroup().equals(currentThread.getThreadGroup());
  }

  @Override
  public DN getDN()
  {
    // This class should only be used internally in the server and not be
    // configurable via the admin framework.
    return null;
  }
}
